package pers.cocoadel.springcloud.service.impl;

import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import pers.cocoadel.springcloud.dao.OrderDao;
import pers.cocoadel.springcloud.domain.Order;
import pers.cocoadel.springcloud.service.StorageService;

import java.math.BigDecimal;
import java.util.Date;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService
{
    private final OrderDao orderDao;

    private final AccountService accountService;

    private final StorageService storageService;

    @Autowired(required = false)
    public OrderServiceImpl(OrderDao orderDao, AccountService accountService, StorageService storageService)
    {
        this.orderDao = orderDao;
        this.accountService = accountService;
        this.storageService = storageService;
    }

    @GlobalTransactional
    @Transactional
    @Override
    public Order createOrder(Long userId, BigDecimal money, Integer count)
    {
        Order order = new Order();
        order.setId(new Date().getTime());
        order.setUserId(userId);
        order.setStatus(0);
        order.setCount(count);
        order.setMoney(money);
        order.setProductId(1L);
        int result = orderDao.create(order);
        log.info("创建订单成功。。。");

        log.info("开始调用库存远程库存服务");
        storageService.decrease(order.getProductId(), order.getCount());
        log.info("减库存成功");

        log.info("开始调用远程账号服务");
        accountService.decrease(order.getUserId(), order.getMoney());
        log.info("扣除账户余额成功");

        orderDao.update(order.getId(), 1);
//        orderDao.update(Long.valueOf("asdfasdf"), 1);
        return order;
    }
}
